package com.angel.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.apache.shiro.authz.permission.WildcardPermission;

/**
 * 自定义shiro 匹配规则
 * @author Rabit
 */

public class CustomerPermissionResolver implements PermissionResolver {
    @Override
    public Permission resolvePermission(String permissionString) {
        //如果含有‘/’则启用自定义的匹配规则，否则使用默认匹配规则
        if (permissionString.trim().contains("/")) {
            return new AntPathPermission(permissionString);
        }
        return new WildcardPermission(permissionString);
    }


    protected class AntPathPermission implements Permission {
        private String permissionString;

        public AntPathPermission(String permissionString) {
            this.permissionString = permissionString;
        }

        public String getPermissionString() {
            return permissionString;
        }

        @Override
        public boolean implies(Permission p) {
            if (!(p instanceof AntPathPermission)) {
                return false;
            }
            AntPathPermission wp = (AntPathPermission) p;
            String wpPerm = wp.getPermissionString();
            if (StringUtils.equals(wpPerm, permissionString)) {
                return true;
            }
            return false;
        }
    }
}
